package cn.imfc.zuul;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.ZuulFilterResult;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: zhangzhigang
 * \* Date: 2018/8/16
 * \* Time: 下午4:52
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 * zuui网关拦截
 */
@Component
@Slf4j
public class MyFillter extends ZuulFilter {

    /**
     * shouldFilter代表这个过滤器是否生效
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /*
    可以在请求被路由之前调用。
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public Object run() {
        RequestContext ctx= RequestContext.getCurrentContext();
        HttpServletRequest request=ctx.getRequest();
        Object accessToken=request.getParameter("token");
        log.info("222222");
        if(accessToken!=null){
            return  null;
        }
        //如果没有token没有返回错误
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(401);
        try {
            ctx.getResponse().getWriter().write("token is empty");
        }catch (Exception e){

        }
        return  null;

    }
}